package demo1;


import java.util.Arrays;
import java.util.Date;

public class HashBuck {
    //哈希桶中的链表节点
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    //站在哈希桶角度，哈希表是Node类型的数组
    public Node[] array;
    public int usedSize;//存放了多少个数据，计算负载因子

    public static final float DEFAULT_LOAD_FACTOR = 0.75f;

    public HashBuck() {
        array = new Node[10];
    }

    //
    public void put(int key, int val) {
        int index = key % array.length;

        //遍历index下标的链表 是否存在key 存在更新value
        //不存在 进行尾插法插入数据
        Node prev = null;
        Node cur = array[index];
        while (cur != null) {
            if (key == cur.key) {
                //更新val
                cur.val = val;
                return;
            }
            prev = cur;
            cur = cur.next;
        }
        //cur == null 链表遍历完成 没有找到这个key，进行尾插或者头插
        Node node = new Node(key, val);
        //尾插法
        if (array[index] == null) {
            array[index] = node;
            usedSize++;
            return;
        }
        prev.next = node;
        usedSize++;

        if (doLoadFactor() > DEFAULT_LOAD_FACTOR) {
            //扩容
            //这种单纯拷贝扩容方法是错误的，因为扩容后需要将链表中冲突的元素重新哈希
            //array = Arrays.copyOf(array, 2 * array.length);
            resize();
        }
    }

    private void resize() {
        Node[] newArray = new Node[2 * array.length];
        //遍历原来数组
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            //遍历每个数组元素(链表)
            while (cur != null) {
                int newIndex = cur.key % newArray.length;//新的数组下标
                //采用头插法，插入到新数组的 newIndex下标
                Node tmp = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = tmp;
            }
        }
        array = newArray;
    }


    //计算当前哈希表负载因子
    private double doLoadFactor() {
        //这里 *1.0是因为要计算出小数
        return usedSize * 1.0f / array.length;
    }


    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }

}
